
#include <librally.h>

Err rp_mutex_init(rp_mutex_t *mutex)
{
	static char fname[] = "rp_mutex_init";
	static char msg[] = "fatal error";
	Err err;
	int ret;
	FLOG_IN(fname);

	ret = pthread_mutex_init(mutex, NULL);
	if (ret)
	{
		rp_log(LOG_CRITICAL, fname, "Cannot initialize the mutex. Error: %d", ret);
		err=  E_ERROR;
	}
	
	FLOG_OUT(fname);
	return E_OK;
}

Err rp_mutex_init_pshared(rp_mutex_t *mutex)
{
	static char fname[] = "rp_mutex_init_pshared";
	static char msg[] = "fatal error";
	Err err;
	pthread_mutexattr_t attr;
	int ret;
	FLOG_IN(fname);
	
	pthread_mutexattr_init(&attr);
	pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
	ret = pthread_mutex_init(mutex, &attr);
	if (ret)
	{
		rp_log(LOG_CRITICAL, fname, "Cannot initialize the mutex. Error: %d", ret);	
		pthread_mutexattr_destroy(&attr);
		return E_ERROR;
	}
	pthread_mutexattr_destroy(&attr);

	FLOG_OUT(fname);
	return E_OK;	
}

Err rp_mutex_destroy(rp_mutex_t *mutex)
{
	static char fname[] = "rp_mutex_destroy";
	static char msg[] = "fatal error";
	Err err;
	int ret;
	FLOG_IN(fname);

	ret = pthread_mutex_destroy(mutex);
	if (ret)
	{
		rp_log(LOG_CRITICAL, fname, "Cannot destroy the mutex. Error: %d", ret);
		return  E_ERROR;
	}

	FLOG_OUT(fname);
	return E_OK;
}

Err rp_mutex_lock(rp_mutex_t *mutex)
{
	static char fname[] = "rp_mutex_destroy";
	static char msg[] = "fatal error";
	Err err;
	int ret;
	FLOG_IN(fname);
	
 	ret = pthread_mutex_lock(mutex);
	if (ret)
	{
		rp_log(LOG_CRITICAL, fname, "Cannot lock the mutex. Error: %d", ret);		
		return (ret == EBUSY)?E_BUSY:E_ERROR;
	}

	FLOG_OUT(fname);
	return E_OK;
}

Err rp_mutex_unlock(rp_mutex_t *mutex)
{
	static char fname[] = "rp_mutex_unlock";
	static char msg[] = "fatal error";
	Err err;
	int ret;
	FLOG_IN(fname);
	
 	ret = pthread_mutex_unlock(mutex);
	if (ret != 0)   
	{
		rp_log(LOG_CRITICAL, fname, "Failed to unlock mutex. Error: %d", ret);		
		return E_ERROR;
	}

	FLOG_OUT(fname);
	return E_OK;
}

